// 测试API连接的脚本
const http = require('http');

function testAPI(port, path) {
  return new Promise((resolve, reject) => {
    const options = {
      hostname: 'localhost',
      port: port,
      path: path,
      method: 'GET',
      timeout: 5000
    };

    const req = http.request(options, (res) => {
      let data = '';
      res.on('data', (chunk) => {
        data += chunk;
      });
      res.on('end', () => {
        resolve({
          status: res.statusCode,
          data: data
        });
      });
    });

    req.on('error', (err) => {
      reject(err);
    });

    req.on('timeout', () => {
      req.destroy();
      reject(new Error('请求超时'));
    });

    req.end();
  });
}

async function runTests() {
  console.log('🔍 开始测试API连接...\n');

  // 测试3001端口健康检查
  try {
    console.log('测试 http://localhost:3001/api/health');
    const result = await testAPI(3001, '/api/health');
    console.log(`✅ 状态码: ${result.status}`);
    console.log(`📄 响应: ${result.data}\n`);
  } catch (error) {
    console.log(`❌ 3001端口测试失败: ${error.message}\n`);
  }

  // 测试3000端口健康检查
  try {
    console.log('测试 http://localhost:3000/api/health');
    const result = await testAPI(3000, '/api/health');
    console.log(`✅ 状态码: ${result.status}`);
    console.log(`📄 响应: ${result.data}\n`);
  } catch (error) {
    console.log(`❌ 3000端口测试失败: ${error.message}\n`);
  }

  // 测试登录接口POST请求
  console.log('测试POST登录接口...');
  testPOSTLogin();
}

function testPOSTLogin() {
  const postData = JSON.stringify({
    username: 'admin',
    password: 'admin123'
  });

  const options = {
    hostname: 'localhost',
    port: 3001,
    path: '/api/auth/login',
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Content-Length': Buffer.byteLength(postData)
    }
  };

  const req = http.request(options, (res) => {
    let data = '';
    res.on('data', (chunk) => {
      data += chunk;
    });
    res.on('end', () => {
      console.log(`POST /api/auth/login 状态码: ${res.statusCode}`);
      console.log(`响应: ${data}`);
    });
  });

  req.on('error', (err) => {
    console.log(`❌ POST请求失败: ${err.message}`);
  });

  req.write(postData);
  req.end();
}

runTests(); 